<?php
namespace app\api\controller;

class Coze extends Base
{
    //对接扣子平台

    //访问令牌
    protected $token = 'pat_yce69DozL0bMvx8B6PqSAEs834migHP0EgCbnvMBgErWp8k5fgUs9zR7odO9iVNt';
    //智能体ID
    protected $bot_id = '7452915373378781219';

    //实例化
    public function obj(){
        return new \app\api\model\Coze();
    }

    //headers
    public function headers(){
        return [
            'Authorization: Bearer ' . $this->token,
            'Content-Type: application/json',
        ];
    }

    /**
     * 对话流程：
     * 发起会话，拿到会话ID，https://api.coze.cn/v3/chat
     * 获取智能体回复，通过会话ID，https://api.coze.cn/v3/chat/message/list
     */

    /**
     * 创建会话
     * POST https://api.coze.cn/v1/conversation/create
     */
    public function hhOne()
    {
        $pas = $this->request->param();
        $imei = isset($pas['imei'])&&$pas['imei'] ? $pas['imei'] : '';
        if (!$imei) {
            return $this->toJson(-2, '没有机器编号');
        }
        $hh = $this->obj()->hhOne($imei);
        if (!$hh) {
            $httpUrl = 'https://api.coze.cn/v1/conversation/create';
            $logid = $this->obj()->logAdd(['url' => $httpUrl]);
            $res = $this->cozeCurl($httpUrl, 2);
            $this->obj()->logModify($logid, ['back' => json_encode($res, JSON_UNESCAPED_UNICODE)]);
            if ($res['code'] < 0) {
                return $this->toJson(-2, $res['msg']);
            }
            $res = $res['data'];
            if ($res['code'] < 0) {
                return $this->toJson(-2, $res['msg']);
            }
            $hh_id = $res['data']['id'];
            $hhOne = $this->obj()->hhAdd($hh_id, $imei);
            if (!$hhOne) {
                return $this->toJson(-2,'fail');
            }
        } else {
            $hh_id = $hh['hh_id'];
        }
        return $this->toJson(0, '', $hh_id);
    }

    /**
     * 用户发起会话
     * POST https://api.coze.cn/v3/chat
     */
    public function hhRun()
    {
        $pas = $this->request->param();
        $cnt = isset($pas['cnt'])&&$pas['cnt'] ? $pas['cnt'] : '';
        $hh_id = isset($pas['hh_id'])&&$pas['hh_id'] ? $pas['hh_id'] : '7453276182402957312';
        if (!$cnt) {
            return $this->toJson(-2, '没有内容');
        }
        //发送到会话
        $httpUrl = 'https://api.coze.cn/v3/chat?conversation_id='.$hh_id;
        $httpData = json_encode([
            'bot_id' => $this->bot_id,
            'user_id' => '111',
            'stream' => false,
            'auto_save_history' => true,
            'additional_messages' => [
                [
                    'role' => 'user',
                    'content_type' => 'text',
                    'content' => $cnt,
                ],
            ],
        ], JSON_UNESCAPED_UNICODE);
        $logid = $this->obj()->logAdd(['url' => $httpUrl, 'req' => $httpData]);
        $res = $this->cozeCurl($httpUrl, 2, $httpData);
        $this->obj()->logModify($logid, ['back' => json_encode($res, JSON_UNESCAPED_UNICODE)]);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        $chat_id = $res['data']['id'];
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        //保存用户消息
        $resChat = $this->obj()->userMsg($hh_id, $chat_id, $cnt);
        if (!$resChat) {
            return $this->toJson(-2, 'fail');
        }
        return $this->toJson(0, '', $res['data']);
    }

    //获取对话
    public function hhget()
    {
        $id = $this->request->param('id', 0); //消息ID
        $res = $this->obj()->hhGet($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    /**
     * 智能体回复
     * GET https://api.coze.cn/v3/chat/message/list
     */
    public function botMsg()
    {
//        $pas = $this->request->param();
//        $chat_id = isset($pas['chat_id'])&&$pas['chat_id'] ? $pas['chat_id'] : '7454397026357477428';
//        if (!$chat_id) {
//            return $this->toJson(-2, '没有对话ID');
//        }
        $msgOne = $this->obj()->msgOne();
        if ($msgOne['code'] < 0) {
            return $this->toJson(-2, '没有记录');
        }
        $hh_id = $msgOne['data']['hh_id'];
        $chat_id = $msgOne['data']['chat_id'];
        //获取智能体回复
        $httpUrl = 'https://api.coze.cn/v3/chat/message/list?conversation_id='.$hh_id.'&chat_id='.$chat_id;
        $logid = $this->obj()->logAdd(['url' => $httpUrl]);
        $res = $this->cozeCurl($httpUrl, 1);
        $this->obj()->logModify($logid, ['back' => json_encode($res, JSON_UNESCAPED_UNICODE)]);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $lists = $res['data'];
        if (!count($lists)) {
            return $this->toJson(-2,'没有回复');
        }
        $cnt = '';
        foreach ($lists as $v) {
            if ($v['type'] == 'answer' && $v['role'] == 'assistant') {
                $cnt = $v['content'];
            }
        }
        if (!$cnt) {
            return $this->toJson(-2,'没匹配的回复');
        }
//        echo '<pre>'; var_dump($cnt); exit;
        //保存智能体消息
        $resChat = $this->obj()->botMsg($chat_id, $cnt);
        if (!$resChat) {
            return $this->toJson(-2, 'fail');
        }
        return $this->toJson(0, '', $cnt);
    }

    /**
     * 构建CURL请求
     * @param string $url 请求地址
     * @param int $method 1get，2post
     * @param string $sring 请求数据
     */
    public function cozeCurl($url, $method = 1, $string = '')
    {
        $headers = $this->headers();
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        if ($method == 2) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=> -1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}